import ipaddress
import socket
import subprocess



def get_local_ip():
    # 获取本机网卡en0的IPv4地址
    ip_address = subprocess.check_output(['ifconfig', 'en0']).decode('utf-8')
    # 提取IPv4地址
    ip_address = ip_address.split('inet ')[1].split(' ')[0]
    return ip_address

def udp_server():
    """UDP服务器，监听5000端口并接收数据"""
    # 创建UDP socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    # 绑定到5000端口
    server_address = ('0.0.0.0', 5000)
    server_socket.bind(server_address)
    
    local_ip = get_local_ip()
    print(f"UDP服务器已启动，监听地址: {local_ip}:{server_address[1]}")
    print("等待接收数据...")
    
    try:
        while True:
            # 接收数据
            data, client_address = server_socket.recvfrom(1024)
            
            # 解码数据并打印
            try:
                message = data.decode('utf-8')
                print(f"收到来自 {client_address} 的数据: {message}")
            except UnicodeDecodeError:
                # 如果无法解码为UTF-8，打印十六进制
                print(f"收到来自 {client_address} 的二进制数据: {data.hex()}")
                
    except KeyboardInterrupt:
        print("\n服务器正在关闭...")
    finally:
        server_socket.close()
        print("服务器已关闭")

if __name__ == "__main__":
    udp_server()
